<template>
  <div class="parent">
    <el-input
      class="inline-input"
      placeholder="人名或拼音首字母"
      v-model="py"
      auto-complete="on"
      clearable
      @keyup.enter.native="submit"
      @keyup.down.native="selectIndex+=selectIndex<result.length-1?1:0"
      @keyup.up.native="selectIndex-=selectIndex>-1?1:0 "
    ></el-input>
    <ul>
      <li v-model="selectIndex" v-for="(item,index) in result" @click="handleSelect(index)"
          :class="{selectItem:index===selectIndex}">{{item.name}}
      </li>
    </ul>
  </div>
</template>

<script>
  import Store from './store'

  export default {
    name: "Search",
    data: () => ({
      py: '',
      result: Store.fetch(),
      selectIndex: -1,
    }),
    methods: {
      submit() {
        console.debug('into submit')

        if (this.selectIndex === -1) {
          if (this.py === '')
            this.$emit('search', null)
        }
        else {
          this.handleSelect(this.selectIndex)
        }
      },
      handleSelect(index) {
        console.debug('into handleSelect')
        this.selectIndex = index
        // this.py = this.result[index].name
        this.$emit('search', this.result[index].name)
      },
    }, watch: {
      py(search_py) {
        console.debug('py change to :', search_py)
        this.selectIndex = -1
        this.result = search_py ? Store.get(search_py) : Store.fetch()
        // if (search_py === '')
        //   this.$emit('search', null)
      }
    }, mounted() {
      console.log('into initSearch')
      this.$emit('search', null)
    }
  }
</script>

<style scoped>
  ul {
    height: 545px;
    overflow-y: scroll;
    padding: 0;
    margin: 5px 0 0 0;
  }

  li {
    list-style-type: none;
    text-align: left;
    padding-left: 15px;
  }

  .selectItem {
    background-color: #333333;
    color: #C0C4CC;
  }

  .parent {
    scrollbar-base-color: transparent;
    scrollbar-darkshadow-color: transparent;
    scrollbar-highlight-color: transparent;
    scrollbar-face-color: transparent;
  }
</style>
